#! /usr/bin/env python
#coding=utf-8

import re,codecs,os,shutil,ConfigParser
from time import strftime, localtime


ini = ConfigParser.ConfigParser()
ini.readfp(open('config.ini'))


#所有的文件都变化为utf8

def addhf(filename):  
    global ini
    '''增加时间戳'''
    try:  
        fp = open(filename)
        content = fp.read()
        dt = '/*' + strftime("%Y-%m-%d %H:%M:%S",localtime()) + ' By ' + ini.get('base','mail') +  '*/\n'
        open(filename, 'w').write('/*begin*/\n' + dt + content +'\n/*end*/')  
    except:  
        pass

def wlog(filename,msg = 'error' ):
    '''出错日志'''
    strLogfileName = strftime("ERROR-"+"%Y-%m-%d.txt",localtime())
    dt = strftime("%Y-%m-%d %H:%M:%S",localtime())
    fp=open(strLogfileName,'a') 
    fp.write(dt +' ') 
    fp.write(filename + ' -> ' + msg + '\n') 
    fp.close()


def trim_bom(str):
    '''清除bom头'''
    if not str:
        return ''
    if len(str) < 3:
        return ''
    if str[:3] == codecs.BOM_UTF8:
        return str[3:]
    return str
    pass


'''处理css类'''
class css:
    '''css处理类'''
    _root = ''
    _file = ''
    
    def __init__(self):
        pass
    
    def hbcss(self,root,file):
        self._root = root   #保存路径
        self._file = file   #保存文件
        fullpath = root + os.sep + file
        fp = open(fullpath,'r') 
        c = fp.read()
        fp.close()

        #判断是否是桥接页面        
        if(file[0]=='@'):
            c = c.replace("'",'"')
            cssList = re.findall('"(.*?.css)"',c) 
            
            allc =  '';
            for cssl in cssList :
                if(os.path.isfile(root + os.sep + cssl)):
                    allc += self.readfile( root+ os.sep +cssl )        
                else:
                    wlog(root + os.sep + cssl, '文件没发现(css)');
            self.writefile (self.rp( allc ), fullpath)
        else :
            #非桥接页面
            if not file[0]=='_' :
                self.writefile (self.rp( c ), fullpath)
                pass
        
    def readfile(self,filepath):
        '''读取文件'''
        fp = open(filepath,'r')
        c  = fp.read()
        c  = trim_bom(c).strip()        
        fp.close()
        return c
    
    def writefile(self,c,fullpath):
        newroot = self.src2build(self._root)
        newfile = self.src2build(newroot + os.sep + self._file)

        if(not os.path.isdir(newroot)):
            os.makedirs(newroot)
        c = trim_bom(c);
        fp = open(newfile, 'w')
        fp.write(c)
        fp.close()
        
        bakFile = newfile+'.bak'
        shutil.copy2(newfile,bakFile)
        
        if(os.path.isfile(newfile)):
            os.remove(newfile)
        
        #压缩css,使用yui
        os.system('java -jar yuicompressor.jar --type css '+ bakFile +' -o '+newfile+' --charset utf-8')
        
        if os.path.isfile(bakFile):
            os.remove(bakFile)
        
        #增加时间戳
        addhf(newfile)
        
        return 1
    
    def src2build(self,fullpath):
        newspath = fullpath.replace('src','build')
        newspath = newspath.replace('@','')
        return newspath
    
    def rp(self,c):
        global ini
        '''过滤相关内容，把一下非常用的中文改为英文'''
        c = c.replace('@charset "utf-8";','')
        c = c.replace("@charset 'utf-8';",'')
        c = c.replace("宋体",'simsun')
        c = c.replace("微软雅黑",'"Microsoft YaHei"')
        
        #时间戳
        c = c.replace('{@time}',strftime("%Y%m%d%M",localtime()))
        
        search  = eval(ini.get('css','search'))
        replace = eval(ini.get('css','replace'))
        
        for i in range(len(search)):
            c = c.replace(search[i],replace[i])
        
        #todo需要做自定义替换
        #c = c.replace("dev",'img01')
        #c = c.replace("src",'build')
        return c
       
class js:
    ''' js处理类 '''

    _root = ''
    _file = ''
    
    def __init__(self):
        pass
    
    def hbjs(self,root,file):
        self._root = root   #保存路径
        self._file = file   #保存文件
        fullpath = root + os.sep + file
        fp = open(fullpath,'r') 
        c = fp.read()
        fp.close()

        #判断是否是桥接页面        
        if file[0]=='@':
            c = c.replace("'",'"')
            jsList = re.findall('src="(.*?.js)"',c)        
            allc =  '';
            for jslist in jsList :
                if(os.path.isfile(root + os.sep + jslist)):
                    allc += self.readfile( root+ os.sep +jslist )        
                else:
                    wlog(root + os.sep + jslist, '文件没发现(js)');
            self.writefile (self.rp(allc), fullpath)
        else :
            if not file[0]=='_' :
                #非桥接页面
                self.writefile (self.rp(c), fullpath)

        
    def readfile(self,filepath):
            '''读取文件'''
            fp = open(filepath,'r')
            c  = fp.read()
            c  = trim_bom(c).strip()        
            fp.close()
            return c
        
    def writefile(self,c,fullpath):
        
        newroot = self.src2build(self._root)
        newfile = self.src2build(newroot + os.sep + self._file)

        if(not os.path.isdir(newroot)):
            os.makedirs(newroot)
        c = trim_bom(c);
        fp = open(newfile, 'w')
        fp.write(c)
        fp.close()
        
        bakFile = newfile+'.bak'
        shutil.copy2(newfile,bakFile)
        
        if(os.path.isfile(newfile)):
            os.remove(newfile)
        
        #压缩css,使用yui
        os.system('java -jar compiler.jar --compilation_level SIMPLE_OPTIMIZATIONS --js '+ bakFile +' --js_output_file '+ newfile)
        
        if os.path.isfile(bakFile):
            os.remove(bakFile)
        
        #增加时间戳
        addhf(newfile)
        
        return 1
    
    def src2build(self,fullpath):
        ''' 替换民转换页面 '''
        newspath = fullpath.replace('src','build')
        newspath = newspath.replace('@','')
        return newspath
    
    def rp(self,c):
        '''过滤相关内容，把一下非常用的中文改为英文'''
        global ini
        
        search  = eval(ini.get('js','search'))
        replace = eval(ini.get('js','replace'))
        
        for i in range(len(search)):
            c = c.replace(search[i],replace[i])
        
        return c


class html:
    '''HTML处理类'''
    _root = ''
    _file = ''
    
    def __init__(self):
        pass
    
    def process(self,root,file):
        
        self._root = root   #保存路径
        self._file = file   #保存文件
        fullpath = root + os.sep + file
        fp = open(fullpath,'r') 
        c = fp.read()
        fp.close()
        c = self.rp(c);
        c = trim_bom(c);
        self.writefile (self.rp(c), fullpath)
        
        
    def writefile(self,c,fullpath):
            newroot = self.src2build(self._root)
            newfile = self.src2build(newroot + os.sep + self._file)
            if(not os.path.isdir(newroot)):
                os.makedirs(newroot)
            c = trim_bom(c);
            fp = open(newfile, 'w')
            fp.write(c)
            fp.close()
            return 1
        
        
    def rp(self,c):
        ''' 替换 '''
        c = c.replace('/src/','/build/')
        c = c.replace('//dev.','//img01.')
        c = c.replace('	','    ')
        c = re.sub(r'@(.*?\.css|.*?\.js)','\\1', c)
        c = c.replace('{@time}',strftime("%Y%m%d%M",localtime()))
        
        '''过滤相关内容，把一下非常用的中文改为英文'''
        global ini
        
        search  = eval(ini.get('html','search'))
        replace = eval(ini.get('html','replace'))
        
        for i in range(len(search)):
            c = c.replace(search[i],replace[i])
        
        return c



    def src2build(self,fullpath):
        ''' 替换民转换页面 '''
        newspath = fullpath.replace('src','build')
        return newspath


class other:
    
    ''' 其他类型 '''
    def __init__(self):
        pass
    
    def cp(self,root,file):
        ''' 复制文件 '''
        oldfile = root + os.sep + file
        newroot = self.src2build(root)
        newfile = self.src2build(oldfile)
        if(not os.path.isdir(newroot)):
            os.makedirs(newroot)

        shutil.copy2(oldfile,newfile)
        pass
   
    def src2build(self,fullpath):
        ''' 替换民转换页面 '''
        return fullpath.replace('src','build')


class png:
        
    _root = ''
    _file = ''
    
    ''' 其他类型 '''
    def __init__(self):
        pass
    
    def Optimizer(self,root,file):
        ''' 复制文件 '''
        self._root = root   #保存路径
        self._file = file   #保存文件
        
        newroot = self.src2build(self._root)
        fullpath = root + os.sep + file
        newfile  = self.src2build(fullpath)
        
        if(not os.path.isdir(newroot)):
            os.makedirs(newroot)
        
        shutil.copy2(fullpath,newfile)
        os.system('PngOptimizerCL -file:"'+newfile+'"')
        pass
   
    def src2build(self,fullpath):
        ''' 替换民转换页面 '''
        newspath = fullpath.replace('src','build')
        return newspath
    